package com.voja.salonschedule;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

import com.voja.AndroidUtils.Application;
import com.voja.AndroidUtils.Application.Click;
import com.voja.AndroidUtils.Application.Command;
import com.voja.AndroidUtils.Application.CommandWrapper;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

public class Services extends BaseChildActivity {
	
	Context context;
	Resources res;
	SharedPreferences prefs;
	
	LayoutInflater 					inflater;
	public static ArrayList<String> services = new ArrayList<String>();
	public static ServicesAdapter 	adapter;
	public static int 				position;
	
	private class ServicesAdapter extends ArrayAdapter<String> {
		ServicesAdapter(Context context, int txtResId, ArrayList<String> services) {
			super(context, txtResId, services);
		}
		
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			String service = getItem(position);
			if (convertView == null) {
				convertView = inflater.inflate(R.layout.service_item, null);
			}
			convertView.setId(position);
			
			TextView txtService = (TextView)convertView.findViewById(R.id.txtService);
			txtService.setText(service);
			
			return convertView;
		}
	} 
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		context  = getApplicationContext();
		res 	 = getResources();
		prefs	 = PreferenceManager.getDefaultSharedPreferences(context);
		inflater = getLayoutInflater();
		
		Application.setContext(this);
		Application.DEFAULT_MESSAGE_TITLE = res.getString(R.string.app_name);
		
		setContentView(R.layout.services);
		initAdapter();
		
		initAd(R.id.adContainer);
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
	    MenuInflater inflater = getMenuInflater();
	    inflater.inflate(R.menu.services, menu);
	    
	    return super.onCreateOptionsMenu(menu);
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
	    switch(item.getItemId()) {
	    case R.id.menuAdd:
	        addService();
	        break;
	    }
	    
	    return super.onOptionsItemSelected(item);
	}
	
	public String[] getServices() {
	    return prefs.getString(Settings.SERVICES_KEY, Settings.SERVICES_DEFAULT).split(Settings.SERVICES_SPLIT);
	}
	
	public void initAdapter() {
		ListView list = (ListView)findViewById(R.id.listServices);
		String[] s = getServices();
		services = new ArrayList<String>();
		for (int i=0; i<s.length; i++) {
			if (s[i].trim().length() > 0) {
				services.add(s[i]);
			}
		}
		sortServices();
		adapter = new ServicesAdapter(this, R.layout.service_item, services);
		list.setAdapter(adapter);
		
		View noServices = findViewById(R.id.noServices);
		noServices.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                addService();
            }
        });
		list.setEmptyView(noServices);
		
		list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> list, View v, int position, long id) {
                editService(position);
            }
        });
	}
	
	public void editService(int position) {
	    final int index = position;
	    String oldServiceName = services.get(position);
	    Command command = new Command(){
            public void execute() {
                EditText edit = (EditText)Application.dialogView;
                String newServiceName = edit.getText().toString().trim();
                if (! newServiceName.equals("")) {
                    
                    services.set(index, newServiceName);
                    sortServices();
                    adapter.notifyDataSetChanged();
                    saveSettings();
                    initAdapter();
                }
            }
        };
        Click ok = new Click("OK", new CommandWrapper(command));
        Application.prompt(res.getString(R.string.Service), oldServiceName, ok);
	}
	
	public void addService() {
		Command command = new Command(){
			public void execute() {
				EditText edit = (EditText)Application.dialogView;
				String service = edit.getText().toString().trim();
				if (! service.equals("")) {
					if (services.indexOf(service)<0) {
						services.add(service);
						sortServices();
						adapter.notifyDataSetChanged();
						
						saveSettings();
						initAdapter();
					} else {
						Application.alert(res.getString(R.string.msgServiceAlreadyExist));
					}
				}
			}
		};
		Click ok = new Click("OK", new CommandWrapper(command));
		Application.prompt(res.getString(R.string.Service), "", ok);
	}
	
	public void sortServices() {
		Collections.sort(services, new Comparator<String>(){
			public int compare(String s1, String s2) {
				return s1.compareToIgnoreCase(s2);
			}
		});
	}
	
	public void deleteService(View v) {
		LinearLayout layout = (LinearLayout)v.getParent();
		position = layout.getId();
		
		CommandWrapper del = new CommandWrapper(new Command() {
			public void execute() {
				services.remove(position);
				if (services.size()>0) {
    				sortServices();
    				adapter.notifyDataSetChanged();
				} else {
				    adapter.notifyDataSetInvalidated();
				}
				saveSettings();
				initAdapter();
			}
		});
		
		Click yes = new Click(res.getString(R.string.Yes), del);
		Click no  = new Click(res.getString(R.string.No), new CommandWrapper(Command.NOOP));
		Application.confirm(res.getString(R.string.msgConfirmDelete), yes, no);
	} 
	
	public void saveSettings() {
		SharedPreferences.Editor editor = prefs.edit(); 
		ListView listServices = (ListView)findViewById(R.id.listServices);
		int size = listServices.getCount();
		if (size>0) {
			services = new ArrayList<String>();
			String prefString = "";
			
			for (int i=0; i<size; i++) {
				if (i>0) {
					prefString += Settings.SERVICES_SPLIT;
				}
				prefString += listServices.getItemAtPosition(i).toString();
				services.add(listServices.getItemAtPosition(i).toString());
			}
			editor.putString(Settings.SERVICES_KEY, prefString);
		} else {
		    editor.putString(Settings.SERVICES_KEY, "");
		}
		
		editor.commit();
	}
}
